import React, { useState, forwardRef } from 'react';
import { Layout, Button } from 'antd';
import Back from '@/pages/mcp-orchestration/components/Back';
import { useRouter } from '@/router/hooks';
import { SvgIcon } from '@/components/icon';
const { Header: AntHeader } = Layout;

interface HeaderProps {
  McpName: string;
  onSave: (is_auto_save?: boolean) => Promise<void>;
  isFormValid?: boolean;
}

export interface HeaderRef {
  switchToKnowledgeTab: () => void;
}

const Header = forwardRef<HeaderRef, HeaderProps>(
  (
    {
      onSave,
      McpName,
      isFormValid = true, // 新增：表单验证状态，默认为true
    },
    ref,
  ) => {
    const [saveStatus, setSaveStatus] = useState(false);
    const router = useRouter();

    return (
      <AntHeader
        style={{
          background: '#FFFFFF',
          height: '56px',
          lineHeight: 'normal',
          padding: '0 12px',
        }}
        className="relative flex items-center justify-between border-b border-[#E5E6EB]"
      >
        <div className="flex">
          <div className="flex items-center gap-2">
            <Back
              title=""
              confirmMessage={
                isFormValid
                  ? '尚未保存，可能会丢失部分信息'
                  : '尚未完成配置,返回后信息将会丢失,确认返回?'
              }
              onOk={() => onSave(false)}
              onBack={() => router.push('/worklayouts/tools/mcpCenter')}
              cancelBack
              okText={isFormValid ? '保存并返回' : '确定'}
              cancelText={isFormValid ? '不保存返回' : '取消'}
            />
            <div className="justify-left flex items-center">
              <span className="justify-left flex items-center gap-1 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
                <span className="text-text-4">MCP中心</span>
                <SvgIcon icon="slash" size={16} />
                <span className="font-semibold text-text-5">{McpName || '未命名MCP工具'}</span>
              </span>
            </div>
          </div>
        </div>
        <div className="mr-2 flex max-w-[40%] items-center justify-end gap-2">
          <Button
            type="primary"
            onClick={async () => {
              try {
                setSaveStatus(true);
                await onSave(false);
              } catch (error) {
                console.error('保存失败:', error);
              } finally {
                setSaveStatus(false);
              }
            }}
            loading={saveStatus}
            disabled={!isFormValid}
          >
            保存
          </Button>
        </div>
      </AntHeader>
    );
  },
);

export default Header;
